package com.dragon.modules.yuegou.service.impl.member;

import com.alipay.api.domain.CardUserInfo;
import com.alipay.api.domain.MerchantCard;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.modules.yuegou.client.ali.request.MarketingCardOpenRequest;
import com.dragon.modules.yuegou.client.ali.request.MarketingCardQueryRequest;
import com.dragon.modules.yuegou.client.ali.request.MarketingCardUpdRequest;
import com.dragon.modules.yuegou.client.ali.request.OauthTokenRequest;
import com.dragon.modules.yuegou.client.ali.response.MarketingCardOpenResponse;
import com.dragon.modules.yuegou.client.ali.response.MarketingCardQueryResponse;
import com.dragon.modules.yuegou.client.ali.response.OauthTokenResponse;
import com.dragon.modules.yuegou.client.ali.service.MemCardService;
import com.dragon.modules.yuegou.entity.member.CardRefEntity;
import com.dragon.modules.yuegou.enums.member.CardRefCardType;
import com.dragon.modules.yuegou.mapper.member.CardRefMapper;
import com.dragon.modules.yuegou.model.member.CardRef;
import com.dragon.modules.yuegou.model.member.TemplateSet;
import com.dragon.modules.yuegou.model.member.WxOpenidRef;
import com.dragon.modules.yuegou.model.pay.BusdConfig;
import com.dragon.modules.yuegou.model.system.Application;
import com.dragon.modules.yuegou.query.member.CardRefQuery;
import com.dragon.modules.yuegou.request.MemberCardOpenRequest;
import com.dragon.modules.yuegou.service.member.CardRefService;
import com.dragon.modules.yuegou.service.member.TemplateSetService;
import com.dragon.modules.yuegou.service.member.WxOpenidRefService;
import com.dragon.modules.yuegou.service.pay.BusdConfigService;
import com.dragon.modules.yuegou.service.system.ApplicationService;
import com.dragon.modules.yuegou.utils.DateUtil;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 会员卡关联表 服务实现
 *
 * @author pbuilder generated
 * @date 2021-11-04 14:36:27
 * @version 2.0
 */
@Service("memCardRefService")
public class CardRefServiceImpl
		extends ServiceImpl<CardRefMapper, CardRefEntity>
		implements CardRefService {
	
	@Autowired
	private MemCardService memCardService;

	@Autowired
	private TemplateSetService templateSetService;
	
    @Autowired
    private WxOpenidRefService wxOpenidRefService;
    
	@Autowired
	private BusdConfigService busdConfigService;

	@Autowired
	private ApplicationService applicationService;
	
	
	@Override
	public void openCard(MemberCardOpenRequest request) {
		TemplateSet templateSet =templateSetService.getTemplateByTemplateId(request.getTemplateId());
		OauthTokenRequest tokenRequest = new OauthTokenRequest();
		tokenRequest.setCode(request.getAuthCode());
		BusdConfig busdConfig =busdConfigService.getBusConfig(templateSet.getBusdId());
		tokenRequest.setAppAuthToken(busdConfig.getAliAppAuthToken());
		OauthTokenResponse tokenResponse =memCardService.oauthToken(tokenRequest);
		if(tokenResponse.isSuccess()) {
			MarketingCardOpenRequest openRequest = new MarketingCardOpenRequest();
			openRequest.setAuthToken(tokenResponse.getAccessToken());
			openRequest.setOutSerialNo(this.getCode());
			openRequest.setCardTemplateId(request.getTemplateId());
			CardUserInfo cardUserInfo = new CardUserInfo();
			cardUserInfo.setUserUniId(tokenResponse.getUserId());
			cardUserInfo.setUserUniIdType("UID");
			openRequest.setCardUserInfo(cardUserInfo);
			MerchantCard cardExtInfo = new MerchantCard();
			cardExtInfo.setOpenDate(new Date());
			String externalCardNo = this.getCode();
			cardExtInfo.setExternalCardNo(externalCardNo);
			cardExtInfo.setLevel("VIP1");
			cardExtInfo.setValidDate(DateUtil.formatStandardDateTime(LocalDateTime.now().plusYears(20)));
			openRequest.setCardExtInfo(cardExtInfo);
			openRequest.setAppAuthToken(busdConfig.getAliAppAuthToken());
			MarketingCardOpenResponse cardOpenResponse =memCardService.marketingCardOpen(openRequest);
			if(cardOpenResponse.isSuccess()) {
				CardRefQuery query = new CardRefQuery();
				query.setTemplateId(cardOpenResponse.getTemplateId());
				query.setAliUserid(tokenResponse.getUserId());
				List<CardRefEntity> list = list(query.toQueryWrapper());
				CardRef cardRef = new CardRef();
				if (CollectionUtils.isNotEmpty(list)){
					cardRef = new CardRef(list.get(0));
				}
				Application application = applicationService.getAppConfig(templateSet.getBusdId());
				WxOpenidRef openidRef =wxOpenidRefService.getByAli(tokenResponse.getUserId(),application.getAppid());
				if(null == cardRef) {
					cardRef = new CardRef();
					cardRef.setId(IdWorker.getIdStr());
					cardRef.setTemplateId(request.getTemplateId());
					cardRef.setAliUserid(tokenResponse.getUserId());
					cardRef.setCardId(cardOpenResponse.getBizCardNo());
					cardRef.setCardNo(externalCardNo);
					cardRef.setCardType(CardRefCardType.ALI);
					cardRef.setCreatedTime(LocalDateTime.now());
					cardRef.setBusdId(templateSet.getBusdId());
					if(null != openidRef) {
						cardRef.setMemberId(openidRef.getMemberId());
					}
					save(cardRef);
				}else {
					cardRef.setCardId(cardOpenResponse.getBizCardNo());
					cardRef.setCardNo(externalCardNo);
					cardRef.setModifiedTime(LocalDateTime.now());
					baseMapper.updateById(cardRef);
				}
			}
		}
	}
	
	
	@Override
	public void synMemPointsAli(String aliUserId,String memberId,String busdId, Integer point) {
		BusdConfig busdConfig =busdConfigService.getBusConfig(busdId);

		CardRefQuery query = new CardRefQuery();
		query.setMemberId(memberId);
		query.setCardType(CardRefCardType.ALI);
		query.busdId().eq(busdId);
		query.del().eq(false);
		List<CardRefEntity> cardRefList = list(query.toQueryWrapper());
		if(CollectionUtils.isEmpty(cardRefList)){
			query = new CardRefQuery();
			query.setAliUserid(aliUserId);
			query.setCardType(CardRefCardType.ALI);
			query.busdId().eq(busdId);
			query.del().eq(false);
			cardRefList = list(query.toQueryWrapper());
		}
		if (CollectionUtils.isNotEmpty(cardRefList)){
			CardRefEntity cardRef = cardRefList.get(0);
			MarketingCardQueryRequest getRequest = new MarketingCardQueryRequest();
			getRequest.setTargetCardNo(cardRef.getCardId());
			getRequest.setAppAuthToken(busdConfig.getAliAppAuthToken());
			MarketingCardQueryResponse queryResponse = memCardService.marketingCardQuery(getRequest);
			if (queryResponse.isSuccess()) {
				MerchantCard merchantCard = queryResponse.getCardInfo();
				MarketingCardUpdRequest request = new MarketingCardUpdRequest();
				request.setAppAuthToken(busdConfig.getAliAppAuthToken());
				request.setTargetCardNo(cardRef.getCardId());
				request.setOccurTime(new Date());
				merchantCard.setPoint(point.toString());
				merchantCard.setValidDate(DateUtil.formatStandardDateTime(
						DateUtil.formatLocalDateTimeByDate(merchantCard.getOpenDate()).plusYears(20)));
				request.setMerchantCard(merchantCard);
				memCardService.marketingCardUpd(request);
			}

			if (memberId.equals(cardRef.getMemberId())){
				CardRef entity = new CardRef();
				entity.setMemberId(memberId);
				entity.setId(cardRef.getId());
				baseMapper.updateById(entity);
			}
		}
	}
	


	private String getCode() {
		String chars ="1234567890";
		return RandomStringUtils.random(16, chars);
	}


	@Override
	public CardRef getByMemberIdAndBusdId(String memberId, String busdId) {
		CardRefQuery query = new CardRefQuery();
		query.setMemberId(memberId);
		query.setBusdId(busdId);
		List<CardRefEntity> list = list(query.toQueryWrapper());
		if (CollectionUtils.isNotEmpty(list)){
			return new CardRef(list.get(0));
		}
		return new CardRef();
	}




}